import { defineStore } from 'pinia'
import { Login, Logout } from '@/api'
import { BaseResponseDto, LoginOutputDto, ResponseDto } from '@/api/types'

export const useUserStore = defineStore({
  // id: 必须的，在所有 Store 中唯一
  id: 'userState',
  // state: 返回对象的函数
  state: () => ({
    // 登录token
    token: null,
    refreshToken: null,
  }),
  getters: {},
  // 可以同步 也可以异步
  actions: {
    // 登录
    login(userName: string, password: string): Promise<ResponseDto<LoginOutputDto>> {
      return new Promise((reslove, reject) => {
        Login({ userName, password })
          .then((result) => {
            if (result.code === 200) {
              this.token = result.data.token
              this.refreshToken = result.data.refreshToken
              localStorage.setItem('token', result.data.token)
              localStorage.setItem('refreshToken', result.data.refreshToken)
              reslove(result)
            } else {
              reject(result)
            }
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    logout(): Promise<BaseResponseDto> {
      return new Promise((reslove, reject) => {
        Logout()
          .then((result) => {
            this.cleanCatch()
            reslove(result)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    cleanCatch() {
      this.token = null
      localStorage.removeItem('token')
      localStorage.removeItem('refreshToken')
    },
  },
  // 进行持久化存储
  persist: {
    // 本地存储的名称
    key: 'userState',
    //保存的位置
    storage: window.localStorage, //localstorage
  },
})
